package output.store.view.component;

import java.io.*;

import output.store.view.base.Statics;
import output.store.view.base.FrameStack;
import output.store.view.component.View3D;


public class DataViewer extends Thread
{
	public long lastFrame = 0;
	public long tMin = 10;
	public View3D view = new View3D();
	
	public DataViewer()
	{
		fillFrames();
		view.setVisible(true);
	}
	
	private void fillFrames()
	{
		int currentFile = 0;
		while(currentFile < 200)
		{
			File file = new File("output/store/data/piece" + currentFile + ".data");
			if(!file.exists())
			{break;}
			else
			{
				System.out.println("loading:    output/store/data/piece" + currentFile + ".data");
				try
				{
					FileInputStream fis = new FileInputStream(file);
					byte[] by = new byte[fis.available()];
					fis.read(by);
					fis.close();
					String str = new String(by);
					parseFile(str);
				}
				catch(Exception e)
				{}
				
				currentFile++;
			}
		}
	}
	
	private void parseFile(String str)
	{
		String[] objs = str.split("\n\n");
		for(int i = 0; i < objs.length; i++)
		{
			if(objs[i].length() > 10)
			{
				FrameStack.addFrame(objs[i]);
			}
		}
	}
	
	//main program
	public void run()
	{
		System.out.println("run");
		lastFrame = System.currentTimeMillis();
		
		while(true)
		{
			//minimum delay
			while(System.currentTimeMillis() < lastFrame + tMin)
			{
				try
				{Thread.sleep(1);}
				catch(InterruptedException e)
				{e.printStackTrace();}
			}
			
			mainLoop();
		}
	}
	
	public double shootInterval = 0.05;
	public double lastShoot = 0;
	public void mainLoop()
	{
		long _time = System.currentTimeMillis();
		Statics.viewTime += 0.0005d * (_time - lastFrame);
		lastFrame = _time;
		
		int currentFrame = FrameStack.getFrame(Statics.viewTime);
		if(currentFrame == -1)
		{
			currentFrame = 0;
			Statics.viewTime = 0;
		}
		else
		{
			Statics.currentFrame = currentFrame;
		}
		
		view.refresh();
		
		if(Statics.viewTime < lastShoot)
		{
			lastShoot = Statics.viewTime;
		}
		if(Statics.viewTime > lastShoot + shootInterval)
		{
			view.shoot();
			lastShoot += shootInterval;
		}
	}
}